package com.hx.study.controller;

import java.util.*;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.hx.common.annotation.Log;
import com.hx.common.core.controller.BaseController;
import com.hx.common.core.domain.AjaxResult;
import com.hx.common.core.domain.entity.SysRole;
import com.hx.common.core.page.TableDataInfo;
import com.hx.common.enums.BusinessType;
import com.hx.common.utils.poi.ExcelUtil;
import com.hx.study.domain.*;
import com.hx.study.service.IPaperRepositoryService;
import com.hx.study.service.IPaperService;
import com.hx.study.service.IQuestionService;
import com.hx.study.service.IUserPaperService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import static com.hx.common.utils.PageUtils.startPage;

/**
 * 用户试卷Controller
 *
 * @author user
 * @date 2022-06-06
 */
@RestController
@RequestMapping("/exam/userPaper")
public class UserPaperController extends BaseController {
    @Autowired
    private IUserPaperService userPaperService;

    /**
     * 查询用户试卷列表
     */
    @PreAuthorize("@ss.hasPermi('exam:userPaper:list')")
    @GetMapping("/list")
    public TableDataInfo list(UserPaper userPaper) {
        startPage();
        List<SysRole> roles = getLoginUser().getUser().getRoles();
        if (roles.stream().noneMatch(o -> o.getRoleId() == 3)) {
            int i = getUserId().intValue();
            userPaper.setUserId(i);
        }

        List<UserPaper> list = userPaperService.selectUserPaperList(userPaper);
        return getDataTable(list);
    }

    /**
     * 导出用户试卷列表
     */
    @PreAuthorize("@ss.hasPermi('exam:userPaper:export')")
    @Log(title = "用户试卷", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, UserPaper userPaper) {
        List<UserPaper> list = userPaperService.selectUserPaperList(userPaper);
        ExcelUtil<UserPaper> util = new ExcelUtil<UserPaper>(UserPaper.class);
        util.exportExcel(response, list, "用户试卷数据");
    }

    /**
     * 获取用户试卷详细信息
     */
    @PreAuthorize("@ss.hasPermi('exam:userPaper:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Integer id) {
        return AjaxResult.success(userPaperService.selectUserPaperById(id));
    }


    @Autowired
    private IPaperService paperService;
    @Autowired
    private IQuestionService questionService;

    @Autowired
    private IPaperRepositoryService paperRepositoryService;
    final String s = "ABCDEFGHIJK";

//    @Autowired
//    private IIntegralLogService integralLogService;

    /**
     * 新增用户试卷
     */
    @PreAuthorize("@ss.hasPermi('exam:userPaper:add')")
    @Log(title = "用户试卷", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody UserPaper userPaper) {
        Long userId = getUserId();
        userPaper.setUserId(userId.intValue());
        if (!StringUtils.hasLength(userPaper.getPaper())) {
            return error("请选择试卷");
        }
        Integer paperId = Integer.parseInt(userPaper.getPaper());
        Paper paper = paperService.selectPaperById(paperId);
        System.out.println("=================================这里");



        userPaper.setPaper(paper.getTitle());
        userPaper.setStatus(null);
        List<UserPaper> userPapers = userPaperService.selectUserPaperList(userPaper);
        if (userPapers.size() >= paper.getLimitCount()) {
            return error("已经参加过该考试");
        }
        userPaper.setStatus("0");
        userPaper.setUserName(getUsername());
        userPaper.setQualifyScore(paper.getQualifyScore());
        userPaper.setTotalTime(paper.getTotalTime());
        userPaper.setUserTime(paper.getTotalTime());
        PaperRepository paperRepository = new PaperRepository();
        paperRepository.setPaperId(paperId);
        List<PaperRepository> paperRepositories = paperRepositoryService.selectPaperRepositoryList(paperRepository);
        List<Question> questionList = new ArrayList<>();
        int totalScore = 0;
        for (PaperRepository repository : paperRepositories) {
            String repositoryId = repository.getRepositoryId();
            Integer radioCount = repository.getRadioCount();
            if (radioCount != null && !radioCount.equals(0)) {//单选题
                Integer score = repository.getRadioScore();
                Question question = new Question();
                question.setRepositoryId(repositoryId);
                question.setQuestionType("1");
                List<Question> questions = questionService.selectRandByRepositoryIdAndType(repositoryId, "1", radioCount);
                for (int i = 0; i < questions.size(); i++) {
                    Question q = questionService.selectQuestionById(questions.get(i).getId());
                    List<QuestionAnswer> questionAnswerList = q.getQuestionAnswerList();
                    Collections.shuffle(questionAnswerList);
                    for (int j = 0; j < questionAnswerList.size(); j++) {
                        QuestionAnswer questionAnswer = questionAnswerList.get(j);
                        questionAnswer.setText(s.charAt(j) + "." + questionAnswer.getText());
                    }
                    Map<String, Object> map = new HashMap<>();
                    map.put("score", score);
                    q.setParams(map);
                    questionList.add(q);
                    totalScore += score;
                }
            }
            Integer multiCount = repository.getMultiCount();
            if (multiCount != null && !multiCount.equals(0)) {
                Integer score = repository.getMultiScore();
                List<Question> questions = questionService.selectRandByRepositoryIdAndType(repositoryId, "2", multiCount);
                for (int i = 0; i < questions.size(); i++) {
                    Question q = questionService.selectQuestionById(questions.get(i).getId());
                    List<QuestionAnswer> questionAnswerList = q.getQuestionAnswerList();
                    Collections.shuffle(questionAnswerList);
                    for (int j = 0; j < questionAnswerList.size(); j++) {
                        QuestionAnswer questionAnswer = questionAnswerList.get(j);
                        questionAnswer.setText(s.charAt(j) + "." + questionAnswer.getText());
                    }
                    Map<String, Object> map = new HashMap<>();
                    map.put("score", score);
                    q.setParams(map);
                    questionList.add(q);
                    totalScore += score;
                }
            }
            Integer fillCount = repository.getFillCount();
//            if (fillCount != null && !fillCount.equals(0)) {
//                Integer score = repository.getFillScore();
//                List<Question> questions = questionService.selectRandByRepositoryIdAndType(repositoryId, "3", fillCount);
//                Collections.shuffle(questions);
//                for (int i = 0; i < fillCount; i++) {
//                    System.out.println(questions.get(i));
//                    System.out.println(questions.get(i).getId());
//                    Question q = questionService.selectQuestionById(questions.get(i).getId());
//                    List<QuestionAnswer> questionAnswerList = q.getQuestionAnswerList();
//                    Collections.shuffle(questionAnswerList);
//                    for (int j = 0; j < questionAnswerList.size(); j++) {
//                        QuestionAnswer questionAnswer = questionAnswerList.get(j);
//                        questionAnswer.setText(s.charAt(j) + "." + questionAnswer.getText());
//                    }
//                    Map<String, Object> map = new HashMap<>();
//                    map.put("score", score);
//                    q.setParams(map);
//                    questionList.add(q);
//                    totalScore += score;
//                }
//            }
        }
        userPaper.setTotalScore(totalScore);
        userPaper.setQuestionList(JSON.toJSONString(questionList));
        return toAjax(userPaperService.insertUserPaper(userPaper));
    }

    /**
     * 修改用户试卷
     */
    @PreAuthorize("@ss.hasPermi('exam:userPaper:edit')")
    @PutMapping
    public AjaxResult edit(@RequestBody UserPaper userPaper) {

        if (userPaper.getStatus() != null && userPaper.getStatus().equals("2")) {//交卷
            userPaper = userPaperService.selectUserPaperById(userPaper.getId());
            if (userPaper == null) {
                return AjaxResult.error("提交试卷不存在");
            }
            System.out.println("=======================================我抄");
            System.out.println(userPaper);
            userPaper.setStatus("2");
            String questionList = userPaper.getQuestionList();
            JSONArray jsonArray = JSON.parseArray(questionList);
            System.out.println("=========================================");
            System.out.println(jsonArray);
            int userScore = 0;
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                System.out.println("=======================================jsonArray");
                System.out.println(jsonObject);
                JSONArray questionAnswerList = jsonObject.getJSONArray("questionAnswerList");
                int flag = 1;
                for (int j = 0; j < questionAnswerList.size(); j++) {
                    System.out.println("================++++++++++++++++++++++++++"+j);
                    System.out.println(questionAnswerList.getJSONObject(j).get("status"));
                    System.out.println(questionAnswerList.getJSONObject(j).getString("checked"));
                    if (!questionAnswerList.getJSONObject(j).get("status").equals(questionAnswerList.getJSONObject(j).getString("checked"))) {
                        flag = 0;
                    }
                }
                Integer score = jsonObject.getJSONObject("params").getInteger("score");
                jsonObject.put("isRight", flag);
                if (flag == 1) {
                    userScore += score;
                    System.out.println("=======================================成绩");
                    System.out.println(score);
                    System.out.println(userScore);
                }
            }
            userPaper.setQuestionList(JSON.toJSONString(jsonArray));
            userPaper.setUserScore(userScore);
        }
        return toAjax(userPaperService.updateUserPaper(userPaper));
    }

    /**
     * 删除用户试卷
     */
    @PreAuthorize("@ss.hasPermi('exam:userPaper:remove')")
    @Log(title = "用户试卷", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids) {
        return toAjax(userPaperService.deleteUserPaperByIds(ids));
    }
}
